package com.example.royalchef.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.royalchef.R;
import com.example.royalchef.base.BaseRecyclerViewAdapter;
import com.example.royalchef.base.BaseRecyclerViewHolder;
import com.example.royalchef.bean.CommentSend;
import com.example.royalchef.utils.PreferUtils;
import com.example.royalchef.utils.UIUtils;
import com.example.royalchef.view.CircleImageView;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * author: Administrator
 * created on: 2017/7/6 11:35
 * description:
 */

public class DynamicCommentActivity extends AppCompatActivity {

    @BindView(R.id.rcv_show_comment)
    RecyclerView rcvComment;
    @BindView(R.id.et_send_content)
    EditText etContent;
    @BindView(R.id.btn_send)
    Button btnSend;
    private ArrayList<CommentSend> commentSends;
    private MyAdapter adapter;
    private String content;
    private CommentSend commentSend;
    private String shareId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_comment);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initView() {
        Intent intent = getIntent();
        shareId = intent.getStringExtra("shareId");
        commentSends = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(DynamicCommentActivity.this, LinearLayoutManager.VERTICAL, false);
        rcvComment.setLayoutManager(manager);
        adapter = new MyAdapter(commentSends, DynamicCommentActivity.this, R.layout.item_home_detail_comment);
        rcvComment.setAdapter(adapter);
        RequestQueue queue = Volley.newRequestQueue(DynamicCommentActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://192.168.12.248:8080/comment/comments.json?shareId=" + shareId + "&page=0&limit=7",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject object = new JSONObject(response);
                            JSONArray data = object.getJSONArray("data");
                            for (int i = 0; i < data.length(); i++) {
                                CommentSend send = new CommentSend();
                                JSONObject jsonObject = data.getJSONObject(i);
                                String content = jsonObject.getString("content");
                                JSONObject user = jsonObject.getJSONObject("user");
                                String name = user.getString("nickname");
                                String avatar = user.getString("avatar");
                                send.setContent(content);
                                send.setAvatar(avatar);
                                send.setName(name);
                                commentSends.add(send);
                            }
                            adapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        queue.add(stringRequest);
    }

    private void initData() {

    }

    private void initListener() {
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                content = etContent.getText().toString();
                String name = PreferUtils.getString("name", "");
                String avatar = PreferUtils.getString("avatar", "");
                if (TextUtils.isEmpty(avatar)) {
                    Intent intent = new Intent(DynamicCommentActivity.this, LoginActivity.class);
                    startActivity(intent);
                    Toast.makeText(DynamicCommentActivity.this, "请登录！", Toast.LENGTH_SHORT).show();
                    return;
                }
                commentSend = new CommentSend(avatar, name, content, "");
                RequestQueue queue = Volley.newRequestQueue(DynamicCommentActivity.this);
                StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://192.168.12.248:8080/comment/comment.json",
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                commentSends.add(commentSend);
                                adapter.notifyDataSetChanged();
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                })

                {
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> map = new HashMap<String, String>();
                        String authToken = PreferUtils.getString("authToken", "");
                        map.put("auth_token", authToken);
                        return map;
                    }

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("shareId", "1");
                        map.put("content", content);
                        return map;
                    }
                };
                queue.add(stringRequest);
            }
        });
    }

    class MyAdapter extends BaseRecyclerViewAdapter<CommentSend> {

        public MyAdapter(ArrayList<CommentSend> list, Context context, int layoutId) {
            super(list, context, layoutId);
        }

        @Override
        public void convert(BaseRecyclerViewHolder holder, CommentSend commentSend, int position, Context context) {
            CircleImageView cirAvatar = (CircleImageView) holder.getView(R.id.civ_home_detail_message_avatar);
            TextView tvName = (TextView) holder.getView(R.id.tv_home_detail_message_name);
            TextView tvContent = (TextView) holder.getView(R.id.tv_home_detail_massage_content);
            Picasso.with(DynamicCommentActivity.this)
                    .load(commentSend.getAvatar())
                    .resize(UIUtils.dip2px(50), UIUtils.dip2px(50))
                    .centerCrop()
                    .config(Bitmap.Config.RGB_565)
                    .into(cirAvatar);
            tvName.setText(commentSend.getName());
            tvContent.setText(commentSend.getContent());
        }
    }
}
